import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../core/services/webrtc_service.dart';
import '../../../core/di/service_locator.dart';
import '../../../core/repositories/chat_repository.dart';
import 'dart:developer' as developer;

class VideoCallPage extends StatefulWidget {
  final String targetUserId;
  final String targetName;
  final String currentUserId;
  final bool isVoiceOnly;

  const VideoCallPage({
    super.key,
    required this.targetUserId,
    required this.targetName,
    required this.currentUserId,
    required this.isVoiceOnly,
  });

  @override
  State<VideoCallPage> createState() => _VideoCallPageState();
}

class _VideoCallPageState extends State<VideoCallPage> {
  final WebRtcService _webrtcService = WebRtcService();
  
  RTCVideoRenderer? _localRenderer;
  RTCVideoRenderer? _remoteRenderer;
  
  MediaStream? _localStream;
  MediaStream? _remoteStream;
  
  bool _isConnecting = true;
  bool _isConnected = false;
  String _statusText = '正在连接...';
  bool _isMuted = false;
  bool _isVideoEnabled = true;
  int _callDuration = 0;
  Timer? _callDurationTimer;
  Timer? _playerCheckTimer;
  Timer? _callTimeoutTimer; // 通话超时定时器（33秒未接听自动挂断）
  
  @override
  void initState() {
    super.initState();
    _initializeCall();
  }
  
  Future<void> _initializeCall() async {
    try {
      // 请求权限
      await _requestPermissions();
      
      // 初始化视频渲染器
      _localRenderer = RTCVideoRenderer();
      _remoteRenderer = RTCVideoRenderer();
      await _localRenderer!.initialize();
      await _remoteRenderer!.initialize();
      
      // 生成流名称（使用排序后的用户ID组合，确保双方使用相同的流名称）
      final ids = [widget.currentUserId, widget.targetUserId]..sort();
      final streamName = '${ids[0]}_${ids[1]}';
      
      // 初始化本地媒体流
      _localStream = await _webrtcService.initLocalStream(
        audio: true,
        video: !widget.isVoiceOnly,
      );
      
      if (_localStream != null && _localRenderer != null) {
        _localRenderer!.srcObject = _localStream;
      }
      
      // 监听连接状态
      _webrtcService.connectionStateStream.listen((state) {
        setState(() {
          _isConnecting = state == WebRtcConnectionState.connecting;
          _isConnected = state == WebRtcConnectionState.connected;
          
          switch (state) {
            case WebRtcConnectionState.connecting:
              _statusText = '正在连接...';
              break;
            case WebRtcConnectionState.connected:
              _statusText = '已连接';
              _startCallDurationTimer();
              _startPlayerCheckTimer(streamName);
              break;
            case WebRtcConnectionState.failed:
              _statusText = '连接失败';
              break;
            default:
              _statusText = '已断开';
          }
        });
      });
      
      // 监听远程流
      _webrtcService.remoteStreamStream.listen((stream) {
        // 关键检查：确保收到的流不是本地流（SRS 回环问题）
        // 通过对象引用比较，而不是 ID 比较
        if (_localStream != null && stream == _localStream) {
          developer.log(
            '⚠️ [VideoCallPage] 收到远程流，但流对象是本地流！拒绝设置到远程渲染器',
            name: 'VideoCallPage',
          );
          // 不设置到远程渲染器，直接返回
          return;
        }
        
        setState(() {
          _remoteStream = stream;
          if (_remoteRenderer != null) {
            // 再次验证：确保不是本地流
            if (stream != _localStream) {
              _remoteRenderer!.srcObject = stream;
              developer.log(
                '✅ [VideoCallPage] 远程视频流已设置到远程渲染器',
                name: 'VideoCallPage',
              );
            } else {
              developer.log(
                '❌ [VideoCallPage] 检测到远程流实际上是本地流，拒绝设置',
                name: 'VideoCallPage',
              );
            }
          }
        });
      });
      
      // 初始化推流连接
      await _webrtcService.initPublishConnection(streamName);
      
      // 初始化拉流连接
      await _webrtcService.initPlayConnection(streamName);
      
      // 启动通话超时定时器（33秒后如果没接听，自动挂断）
      _startCallTimeout();
      
    } catch (e) {
      developer.log('初始化通话失败: $e', name: 'VideoCallPage');
      if (mounted) {
        setState(() {
          _statusText = '初始化失败: $e';
          _isConnecting = false;
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('通话初始化失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
  
  Future<void> _requestPermissions() async {
    // 检查是否在模拟器上运行
    final isSimulator = !kIsWeb && (Platform.isIOS || Platform.isAndroid);
    // 注意：无法直接检测是否是模拟器，但可以检测权限状态
    
    if (widget.isVoiceOnly) {
      // 仅语音通话，只需要麦克风权限
      final micStatus = await Permission.microphone.request();
      if (!micStatus.isGranted) {
        String errorMessage = '需要麦克风权限才能进行语音通话';
        
        // 如果权限被永久拒绝，引导用户去设置
        if (micStatus.isPermanentlyDenied) {
          errorMessage += '\n\n权限已被永久拒绝，请在设置中手动开启麦克风权限';
          
          // 显示对话框，询问是否打开设置
          if (mounted) {
            final shouldOpen = await showDialog<bool>(
              context: context,
              builder: (context) => AlertDialog(
                title: const Text('需要麦克风权限'),
                content: const Text('应用需要麦克风权限才能进行语音通话。\n\n如果在模拟器上运行，请：\n1. iOS 模拟器：设置 → 模拟器 → 权限 → 开启麦克风\n2. Android 模拟器：设置 → 应用 → violet_mobile → 权限 → 开启麦克风\n\n如果在真机上运行，请在系统设置中开启权限。'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: const Text('去设置'),
                  ),
                ],
              ),
            );
            
            if (shouldOpen == true) {
              await openAppSettings();
            }
          }
        } else {
          // 权限被拒绝但不是永久拒绝，可能是模拟器的问题
          if (mounted) {
            await showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: const Text('需要麦克风权限'),
                content: const Text('应用需要麦克风权限才能进行语音通话。\n\n如果在模拟器上运行：\n• iOS 模拟器：设置 → 模拟器 → 权限 → 开启麦克风\n• Android 模拟器：设置 → 应用 → violet_mobile → 权限 → 开启麦克风\n\n提示：模拟器可能不支持完整的权限管理，建议在真机上测试通话功能。'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('知道了'),
                  ),
                ],
              ),
            );
          }
        }
        
        throw Exception(errorMessage);
      }
    } else {
      // 视频通话，需要相机和麦克风权限
      final cameraStatus = await Permission.camera.request();
      final micStatus = await Permission.microphone.request();
      
      String? errorMessage;
      bool shouldOpenSettings = false;
      
      if (!cameraStatus.isGranted) {
        errorMessage = '需要相机权限才能进行视频通话';
        if (cameraStatus.isPermanentlyDenied) {
          errorMessage += '\n\n权限已被永久拒绝，请在设置中手动开启相机权限';
          shouldOpenSettings = true;
        }
      }
      
      if (!micStatus.isGranted) {
        if (errorMessage != null) {
          errorMessage += '\n\n同时需要麦克风权限';
        } else {
          errorMessage = '需要麦克风权限才能进行视频通话';
        }
        if (micStatus.isPermanentlyDenied) {
          errorMessage += '\n\n权限已被永久拒绝，请在设置中手动开启麦克风权限';
          shouldOpenSettings = true;
        }
      }
      
      if (errorMessage != null) {
        // 如果权限被永久拒绝，显示对话框引导用户去设置
        if (shouldOpenSettings && mounted) {
          final shouldOpen = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('需要权限'),
              content: const Text('应用需要相机和麦克风权限才能进行视频通话。\n\n如果在模拟器上运行，请：\n1. iOS 模拟器：设置 → 模拟器 → 权限 → 开启相机和麦克风\n2. Android 模拟器：设置 → 应用 → violet_mobile → 权限 → 开启相机和麦克风\n\n如果在真机上运行，请在系统设置中开启权限。'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('去设置'),
                ),
              ],
            ),
          );
          
          if (shouldOpen == true) {
            await openAppSettings();
          }
        } else if (errorMessage != null && mounted) {
          // 权限被拒绝但不是永久拒绝，显示提示
          await showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('需要权限'),
              content: const Text('应用需要相机和麦克风权限才能进行视频通话。\n\n如果在模拟器上运行：\n• iOS 模拟器：设置 → 模拟器 → 权限 → 开启相机和麦克风\n• Android 模拟器：设置 → 应用 → violet_mobile → 权限 → 开启相机和麦克风\n\n提示：模拟器可能不支持完整的权限管理，建议在真机上测试通话功能。'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('知道了'),
                ),
              ],
            ),
          );
        }
        
        throw Exception(errorMessage);
      }
    }
  }
  
  void _startCallDurationTimer() {
    _callDurationTimer?.cancel();
    _callDurationTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          _callDuration++;
        });
      }
    });
  }
  
  void _startPlayerCheckTimer(String streamName) {
    _playerCheckTimer?.cancel();
    _playerCheckTimer = Timer.periodic(const Duration(seconds: 3), (timer) async {
      final players = await _webrtcService.checkStreamPlayers(streamName);
      developer.log('流播放者数量: $players', name: 'VideoCallPage');
      
      if (players > 0 && !_isConnected) {
        setState(() {
          _isConnected = true;
          _statusText = '已连接';
        });
        // 对方已接听，停止超时定时器
        _stopCallTimeout();
      }
    });
  }
  
  // 启动通话超时定时器（33秒后如果没接听，自动挂断）
  void _startCallTimeout() {
    _stopCallTimeout();
    _callTimeoutTimer = Timer(const Duration(seconds: 33), () {
      // 如果33秒后还没有连接成功，说明对方没接听，自动挂断
      if (mounted && !_isConnected) {
        developer.log('通话超时（33秒内未接听），自动挂断', name: 'VideoCallPage');
        _endCall();
      }
    });
  }
  
  // 停止通话超时定时器
  void _stopCallTimeout() {
    _callTimeoutTimer?.cancel();
    _callTimeoutTimer = null;
  }
  
  String _formatDuration(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    
    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    } else {
      return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    }
  }
  
  Future<void> _toggleMute() async {
    await _webrtcService.toggleMute();
    setState(() {
      _isMuted = _webrtcService.isMuted;
    });
  }
  
  Future<void> _toggleVideo() async {
    if (widget.isVoiceOnly) return;
    
    await _webrtcService.toggleVideo();
    setState(() {
      _isVideoEnabled = _webrtcService.isVideoEnabled;
    });
  }
  
  Future<void> _switchCamera() async {
    if (widget.isVoiceOnly) return;
    
    await _webrtcService.switchCamera();
  }
  
  Future<void> _endCall() async {
    _callDurationTimer?.cancel();
    _playerCheckTimer?.cancel();
    _stopCallTimeout();
    
    // 发送通话取消消息，通知对方（桌面端等）通话已结束
    try {
      final serviceLocator = ServiceLocator();
      final chatRepository = serviceLocator.chatRepository;
      
      // 获取当前用户的 open_id
      final currentUser = widget.currentUserId;
      final targetUser = widget.targetUserId;
      
      if (currentUser.isNotEmpty && targetUser.isNotEmpty) {
        await chatRepository.sendCallCancel(
          fromId: currentUser,
          toId: targetUser,
        );
        developer.log('已发送通话取消消息', name: 'VideoCallPage');
      }
    } catch (e) {
      developer.log('发送通话取消消息失败: $e', name: 'VideoCallPage');
      // 即使发送失败，也继续执行挂断流程
    }
    
    await _webrtcService.dispose();
    
    if (_localRenderer != null) {
      await _localRenderer!.dispose();
    }
    if (_remoteRenderer != null) {
      await _remoteRenderer!.dispose();
    }
    
    if (mounted) {
      Navigator.of(context).pop();
    }
  }
  
  @override
  void dispose() {
    _callDurationTimer?.cancel();
    _playerCheckTimer?.cancel();
    _stopCallTimeout();
    _webrtcService.dispose();
    _localRenderer?.dispose();
    _remoteRenderer?.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Stack(
          children: [
            // 远程视频（全屏）
            if (_remoteRenderer != null && !widget.isVoiceOnly)
              Positioned.fill(
                child: RTCVideoView(
                  _remoteRenderer!,
                  mirror: false,
                  objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
                ),
              )
            else if (widget.isVoiceOnly || _remoteStream == null)
              Positioned.fill(
                child: Container(
                  color: Colors.black87,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircleAvatar(
                          radius: 60,
                          backgroundColor: Colors.grey[800],
                          child: Text(
                            widget.targetName.isNotEmpty
                                ? widget.targetName[0].toUpperCase()
                                : '?',
                            style: const TextStyle(
                              fontSize: 48,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        const SizedBox(height: 24),
                        Text(
                          widget.targetName,
                          style: const TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          _statusText,
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey[400],
                          ),
                        ),
                        if (_isConnected && _callDuration > 0) ...[
                          const SizedBox(height: 8),
                          Text(
                            _formatDuration(_callDuration),
                            style: const TextStyle(
                              fontSize: 20,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
            
            // 本地视频（小窗口，右上角）
            if (_localRenderer != null && !widget.isVoiceOnly && _isVideoEnabled)
              Positioned(
                top: 16,
                right: 16,
                child: Container(
                  width: 120,
                  height: 160,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.white, width: 2),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: RTCVideoView(
                      _localRenderer!,
                      mirror: true,
                      objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
                    ),
                  ),
                ),
              ),
            
            // 控制按钮（底部）
            Positioned(
              bottom: 40,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 静音按钮
                  _buildControlButton(
                    icon: _isMuted ? Icons.mic_off : Icons.mic,
                    label: _isMuted ? '取消静音' : '静音',
                    onPressed: _toggleMute,
                    backgroundColor: _isMuted ? Colors.red : Colors.grey[800]!,
                  ),
                  
                  const SizedBox(width: 16),
                  
                  // 视频开关按钮（仅视频通话）
                  if (!widget.isVoiceOnly)
                    _buildControlButton(
                      icon: _isVideoEnabled ? Icons.videocam : Icons.videocam_off,
                      label: _isVideoEnabled ? '关闭视频' : '开启视频',
                      onPressed: _toggleVideo,
                      backgroundColor: _isVideoEnabled ? Colors.grey[800]! : Colors.red,
                    ),
                  
                  if (!widget.isVoiceOnly) const SizedBox(width: 16),
                  
                  // 切换摄像头按钮（仅视频通话）
                  if (!widget.isVoiceOnly)
                    _buildControlButton(
                      icon: Icons.flip_camera_ios,
                      label: '切换摄像头',
                      onPressed: _switchCamera,
                      backgroundColor: Colors.grey[800]!,
                    ),
                  
                  if (!widget.isVoiceOnly) const SizedBox(width: 16),
                  
                  // 挂断按钮
                  _buildControlButton(
                    icon: Icons.call_end,
                    label: '挂断',
                    onPressed: _endCall,
                    backgroundColor: Colors.red,
                  ),
                ],
              ),
            ),
            
            // 顶部信息栏
            Positioned(
              top: 16,
              left: 16,
              right: 16,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    if (widget.isVoiceOnly || _remoteStream == null)
                      CircleAvatar(
                        radius: 20,
                        backgroundColor: Colors.grey[800],
                        child: Text(
                          widget.targetName.isNotEmpty
                              ? widget.targetName[0].toUpperCase()
                              : '?',
                          style: const TextStyle(
                            fontSize: 18,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            widget.targetName,
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          if (_isConnected && _callDuration > 0)
                            Text(
                              _formatDuration(_callDuration),
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[300],
                              ),
                            )
                          else
                            Text(
                              _statusText,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[300],
                              ),
                            ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildControlButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
    required Color backgroundColor,
  }) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 56,
          height: 56,
          decoration: BoxDecoration(
            color: backgroundColor,
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: onPressed,
              borderRadius: BorderRadius.circular(28),
              child: Icon(
                icon,
                color: Colors.white,
                size: 28,
              ),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.white,
          ),
        ),
      ],
    );
  }
}

